﻿using System;
using System.Web;

namespace Facebook.Web
{
    public class FacebookApplication : HttpApplication
    {
        public event EventHandler FacebookContextInit;

        public override void Init()
        {
            base.Init();

            this.BeginRequest += new EventHandler(FacebookApplication_BeginRequest);
            this.FacebookContextInit += new EventHandler(FacebookApplication_FacebookContextInit);
        }

        protected internal void OnFacebookContextInit(Object sender)
        {
            if (this.FacebookContextInit != null)
            {
                this.FacebookContextInit(sender, EventArgs.Empty);
            }
        }

        void FacebookApplication_FacebookContextInit(Object sender, EventArgs e)
        {
            var context = (FacebookWebContext)sender;            
            if(this.Application["__FB_FEED_INIT_" + context.ApiKey] == null)
            {
                if (Configuration.FacebookSection.IsConfigured)
                {
                    var config = Configuration.FacebookSection.Current;
                    if (!String.IsNullOrEmpty(Configuration.FacebookSection.Current.FeedTemplateConfigSource))
                    {
                        var templates = Configuration.FeedTemplates.Get(); ;
                        if (templates.Count > 0)
                        {
                            context.Feed.InitFeedTemplates();
                        }
                    }
                }
                this.Application["__FB_FEED_INIT_" + context.ApiKey] = true;
            }
        }

        void FacebookApplication_BeginRequest(Object sender, EventArgs e)
        {
            if (!FacebookWebContext.IsReady(this.Context))
            {
                FacebookWebContext.Init(this.Context);
            }
        }
    }
}